//
//  WPLoadView.m
//  health
//
//  Created by apple on 2021/11/17.
//  Copyright © 2021 zglee. All rights reserved.
//

#import "WPLoadView.h"

@interface WPLoadView ()

@property (weak, nonatomic) IBOutlet UIImageView *loadImageView;
@property (nonatomic,  strong) UIWindow *overlayWindow;
@property (assign, nonatomic)BOOL isClose;
@end
@implementation WPLoadView

/**
 单例
 */
+ (instancetype)shared
{
    static WPLoadView *instance = nil;
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        instance = [[NSBundle mainBundle]loadNibNamed:NSStringFromClass([self class]) owner:self options:nil].firstObject;
        instance.frame = SCREEN_MAIN;
//        [instance actionAnimation];
    });
    return instance;
}
- (void)showLoadView {
    [WPLoadView.shared.overlayWindow addSubview:WPLoadView.shared];
    [WPLoadView.shared startAnimation];

}

//+ (instancetype)showLoadView{
//    WPLoadView *loadView = [[NSBundle mainBundle]loadNibNamed:NSStringFromClass([self class]) owner:self options:nil].firstObject;
//    loadView.frame = SCREEN_MAIN;
//    [loadView.overlayWindow addSubview:loadView];
//    [loadView actionAnimation];
//    //主线程演示操作
//    dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(15 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
//        if (!loadView.isClose) {
//            [loadView closeLoadView];
//            [RoyHud showToast:@"请求超时"];
//        }
//    });
//    return loadView;
//}

- (void)closeLoadView{
    [[WPLoadView shared] stopAnimation];
    [[WPLoadView shared] removeFromSuperview];
}

- (void)actionAnimation{
    // 一秒钟旋转几圈
        CGFloat circleByOneSecond = 4.f;
        // 执行动画
        [UIView animateWithDuration:1.f / circleByOneSecond
                              delay:0
                            options:UIViewAnimationOptionCurveLinear
                         animations:^{
            [WPLoadView shared].loadImageView.transform = CGAffineTransformRotate([WPLoadView shared].loadImageView.transform, M_PI_2);
        }
                         completion:^(BOOL finished){
//            [[WPLoadView shared] actionAnimation];
        }];
    
}
- (void)startAnimation

{
    CABasicAnimation* rotationAnimation = [CABasicAnimation animationWithKeyPath:@"transform.rotation.z"];

    rotationAnimation.toValue = [NSNumber numberWithFloat: M_PI * 2.0 ];

    rotationAnimation.duration = 2;

    rotationAnimation.cumulative = YES;

    rotationAnimation.repeatCount = HUGE_VALF;

    [[WPLoadView shared].loadImageView.layer addAnimation:rotationAnimation forKey:@"rotationAnimation"];

}


- (void)stopAnimation

{
    [[WPLoadView shared].loadImageView.layer removeAllAnimations];

}

#pragma mark - 懒加载
- (UIWindow *)overlayWindow {
    
    UIWindow *window = [[[UIApplication sharedApplication] delegate] window];
    if (!window) {
        window = [[UIApplication sharedApplication].windows objectAtIndex:0];
    }
    _overlayWindow = window;
    return _overlayWindow;
}
@end
